#######################################
# 本程序用于将numpy数组保存为C语言头文件
#######################################
import numpy as np

fmt='''
#ifndef {0}
#define {0}

#include "dtype.h" // you should specify data type in this file

const dtype {1}{2}={{
{3}
}};

#endif

'''

def get_dim_str(a):
    return '[' + ']['.join(list(map(str, a.shape))) + ']'

# a: np.array
# col: Columns
def np2str(a, col=8):
    ret = ''
    cnt = 0
    for var in a.flatten():
        ret += '{0}, '.format(str(var))
        cnt += 1
        if cnt % col == col -1:
            ret += '\n'
    return ret

def np2c_header(a, fname='data'):
    with open(fname + '.h', 'w') as fp:
        fp.write(
            fmt.format(
                '_' + fname.upper() + '__H_',
                fname,
                get_dim_str(a),
                np2str(a)
            )
        )

def test():
    # a = np.random.randn(1,6,28,28)
    a = (np.random.randn(1,6,28,28)*2**12).astype(np.int32)
    print(get_dim_str(a))
    print(np2str(a,4))
    np2c_header(a)
    pass

if __name__ == "__main__":
    test()